'''
Author: xialang333@gmail.com
Date: 2024-08-19 15:33:14
LastEditTime: 2024-08-19 16:18:05
# 公共函数类
'''
import pymysql
import logging
from urllib import parse
from logging.handlers import RotatingFileHandler

from config import *


# 连接数据库
class ConnDB:
    def __init__(self):
        self.user = mysql_user
        self.passwd =  parse.unquote_plus(mysql_passwd)
        self.host = mysql_host
        self.port = mysql_port
        self.database = mysql_db
        self.charset = charset
        self.connection = None
        self.cursor = None
 
    # 连接
    def connect(self):
        self.connection = pymysql.connect(host=self.host, user=self.user,
                                          password=self.passwd, database=self.database,
                                          port=self.port, charset=self.charset)
        self.cursor = self.connection.cursor()
 
    # 非查询语法
    def execute_query(self, query, params=()):
        if self.connection is None:
            self.connect()
        self.cursor.execute(query, params)
        self.connection.commit()
 
    # 查询语法
    def fetch_all(self, query, params=()):
        if self.connection is None:
            self.connect()
        self.cursor.execute(query, params)
        return self.cursor.fetchall()
 
    # 关闭连接
    def close(self):
        if self.connection is not None:
            self.cursor.close()
            self.connection.close()


# 日志记录
class CustomLogger:
    def __init__(self, name, log_file='app.log', max_bytes=1024*1024, backup_count=5):
        """
        初始化日志记录器
        
        :param name: 日志记录器名称
        :param log_file: 日志文件路径
        :param max_bytes: 单个日志文件的最大大小
        :param backup_count: 最多保留的日志文件数量
        """
        self.logger = logging.getLogger(name)
        self.logger.setLevel(logging.DEBUG)  # 设置最低日志级别

        # 创建文件 handler
        file_handler = RotatingFileHandler(log_file, maxBytes=max_bytes, backupCount=backup_count)
        file_handler.setLevel(logging.DEBUG)

        # 创建控制台 handler
        console_handler = logging.StreamHandler()
        console_handler.setLevel(logging.INFO)

        # 创建 formatter
        formatter = logging.Formatter('%(asctime)s [%(levelname)s] %(message)s')
        file_handler.setFormatter(formatter)
        console_handler.setFormatter(formatter)

        # 将 handlers 添加到 logger
        self.logger.addHandler(file_handler)
        self.logger.addHandler(console_handler)

    def get_logger(self):
        """
        返回配置好的 logger 实例
        """
        return self.logger